﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SqliteORM;
using ChgDoc.Entity;

namespace ChgDoc.Entity
{
    [Table]
    public class ArticleTag : TableBase<ArticleTag>
    {
        [ForeignKey( typeof( Article ) )]
        public long ArticleId { get; set; }

        [ForeignKey( typeof( Tag ) )]
        public long TagId { get; set; }
		
		[Field]
		public int SortOrder { get; set; }

        internal static void Add(long articleId, long tagId)
        {
            Do(ad => ad.CreateUpdate(new ArticleTag() { ArticleId = articleId, TagId = tagId }));
        }

        internal static void Delete(long articleId, long tagId)
        {
            Do(ad => ad.Delete(Where.And(Where.Equal("articleId", articleId), Where.Equal("tagId", tagId))));
        }
		
		internal static List<ArticleSortDisplay> ArticlesFor(long tagId)
        {
            List<ArticleSortDisplay> results = new List<ArticleSortDisplay>();

            using (var sql = new DirectSql())
            {
                sql.Execute("select a.Id, a.Title, at.SortOrder from article a join articletag at on at.articleid = a.id where at.tagid = " + tagId + " order by at.sortorder",
                    objArr =>
                    {
                        var row = new ArticleSortDisplay();
                        row.ArticleId = (long)objArr[0];
                        row.Title = (string)objArr[1];
                        row.SortOrder = (Convert.IsDBNull(objArr[2]) ? 0 : (int)objArr[2]) ;
                        results.Add(row);

                        return true;
                    });
            }

            return results;
        }

    }
}